import Vue from 'vue'
import config from './config.js'
import vueResource from 'vue-resource' // 通信类
Vue.use(vueResource);

Vue.use(function(Vue, options) {
  Vue.prototype.cUrl = window.CONFIG.cUrl
  /*example: this.$_reSource(function(data){}.bind(this))*/
  Vue.prototype.$_reSource = function (path, cb, data, type, cb2, path2) {
    this.$Loading.config({
      color: '#28c4fe', // 加载条颜色
      failedColor: '#fd0404',
      height: 2
    });
    this.$Loading.start()
    if (data && JSON.stringify(data) == '{}') data = ''
    if ('get' == type) {
      if(!data.per_page) {
        if(data) {
          data.per_page = '9999';
        }
      }
      if (!data) {} // data={}; data.per_page = '9999'
    }
    var sdata = '';
    var callBack = function(response) {
      this.$Loading.finish();
      if (cb) cb.call(this, response.body, response);
    }.bind(this);
    var callErrBack = function(response) {

      this.$Loading.error();
      if(response.status == 401) {
        if (this.login == false) {
          this.$notify.error({
            title: '用户密码错误',
            message: '请检查用户名或者密码'
          });
          this.loading = false;
          return;
        } else {
          this.$Notice.error({
            title: '登陆超时',
            desc: '点击关闭重新登陆'
          });
        }
        this.loading = false;
        localStorage.clear();
        window.document.title = '登陆跳转中...'
        setTimeout(function() {
          window.location.reload();
        }, 5000);
        return;
      }
      var desc = '';
      if (response.body.error) {
        desc = response.body.error
      } else desc = response.body.message;
      this.$Notice.error({
        title: '请求出错',
        desc: desc
      });
      if (cb2) cb2.call(this, response.body)
    }
    if (data && (type === 'get' || type === 'get')) {
      sdata = encodeURI(JSON.stringify(data).toSearchStr())
    }
    var path = this.cUrl + path + sdata
    if (path2) {
      path = window.CONFIG.domain + path2
    }
    if ('post' === type) {
      this.$http.post(path, data).then(callBack, callErrBack)
    } else if ('delete' === type) {
      this.$http.delete(path).then(callBack, callErrBack)
    } else if ('put' === type) {
      this.$http.put(path, data).then(callBack, callErrBack)
    } else {
      this.$http.get(path).then(callBack, callErrBack)
    }
  } // 通讯组件
  Vue.prototype.$_setUuid = function (uuid) {
    // if(uuid) Vue.prototype.maker_uuid = uuid
    // if(uuid) Vue.prototype.assistants_uuid = uuid
    Vue.http.options.headers = {
      Authorization: 'Bearer ' + localStorage.getItem('token')
    }
    window.document.title = '后台'
  }
}) // 配置、类库、组件封装挂载
